package com.lq.mytool.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author noah.xie
 * @date 2020/11/18
 */
@Component
public class SpringApplicationUtil implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(com.lq.mytool.utils.SpringApplicationUtil.class);
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        com.lq.mytool.utils.SpringApplicationUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        T obj;
        try {
            obj = applicationContext.getBean(clazz);
        } catch (Exception e) {
            obj = null;
            LOGGER.error("get bean error!", e);
        }
        return obj;
    }

    public static <T> List<T> getBeansOfType(Class<T> clazz) {
        return new ArrayList<>(getBeansMapOfType(clazz).values());
    }

    public static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> Map<String, T> getBeansMapOfType(Class<T> clazz) {
        Map<String, T> map;
        try {
            map = applicationContext.getBeansOfType(clazz);
        } catch (Exception e) {
            map = null;
            LOGGER.error("get bean error!", e);
        }
        return map == null ? new HashMap<>() : map;
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> anno) {
        Map<String, Object> map;
        try {
            map = applicationContext.getBeansWithAnnotation(anno);
        } catch (Exception e) {
            map = null;
        }
        return map;
    }
}